<template>
  <div class="role-page art-full-height">
    <RoleSearch
      v-show="showSearchBar"
      v-model="searchForm"
      @search="handleSearch"
      @reset="resetSearchParams"
    ></RoleSearch>

    <ElCard
      class="art-table-card"
      shadow="never"
      :style="{ 'margin-top': showSearchBar ? '12px' : '0' }"
    >
      <ArtTableHeader
        v-model:columns="columnChecks"
        v-model:showSearchBar="showSearchBar"
        :loading="loading"
        @refresh="refreshData"
      >
        <template #left>
          <ElSpace wrap style="margin-right: 5px">
            <ElButton type="danger" v-auth="'auth:admin:logdel'" @click="deleteRole()" v-ripple
              >删除日志</ElButton
            >
          </ElSpace>
        </template>
      </ArtTableHeader>

      <!-- 表格 -->
      <ArtTable
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        @selection-change="handleSelectionChange"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      >
      </ArtTable>
    </ElCard>
  </div>
</template>

<script setup lang="ts">
  import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
  import { useTable } from '@/composables/useTable'
  import { fetchAdminLogList, deleteAdminLogApi } from '@/api/system-manage'
  import RoleSearch from './modules/role-search.vue'
  import { ElTag, ElMessageBox, ElTooltip } from 'element-plus'
  import { useAuth } from '@/composables/useAuth'
  const { hasAuth } = useAuth()
  defineOptions({ name: 'Role' })

  type RoleListItem = Api.SystemManage.RoleListItem
  // 选中行
  const selectedRows = ref<RoleListItem[]>([])
  // 搜索表单
  const searchForm = ref({
    search: undefined,
    type: undefined,
    created_at: undefined
  })

  const showSearchBar = ref(false)

  const {
    columns,
    columnChecks,
    data,
    loading,
    pagination,
    getData,
    searchParams,
    resetSearchParams,
    handleSizeChange,
    handleCurrentChange,
    refreshData
  } = useTable({
    // 核心配置
    core: {
      apiFn: fetchAdminLogList,
      apiParams: {
        current: 1,
        size: 20
      },
      // 排除 apiParams 中的属性
      excludeParams: ['daterange'],
      columnsFactory: () => [
        { type: 'selection' }, // 勾选列
        {
          prop: 'id',
          label: 'ID',
          width: 100
        },
        {
          prop: 'username',
          label: '操作人账号',
          minWidth: 120
        },
        {
          prop: 'url',
          label: '操作方法',
          minWidth: 120,
          formatter: (row: any) => {
            return h(
              ElTooltip,
              { content: row.user_agent || '', placement: 'top' },
              {
                default: () => row.url
              }
            )
          }
        },
        {
          prop: 'ip',
          label: '上次登录 IP',
          width: 240,
          // checked: false, // 隐藏列
          formatter: (row: any) =>
            h('div', {}, [
              h('p', { class: 'user-ip' }, row.ip || '无IP'),
              h('p', { class: 'user-area' }, row.last_login_area || '未知地区')
            ])
        },
        {
          prop: 'type',
          label: '操作类型',
          width: 100,
          formatter: (row: any) => {
            const typeMap = {
              1: { type: 'success', text: '添加' },
              2: { type: 'info', text: '编辑' },
              3: { type: 'danger', text: '删除' },
              4: { type: 'warning', text: '登录' }
            }
            const statusConfig = typeMap[row.type as keyof typeof typeMap] || {
              type: 'default',
              text: '未知'
            }
            return h(
              ElTooltip,
              { content: row.data || '无类型', placement: 'top' },
              {
                default: () =>
                  h(
                    ElTag,
                    {
                      type: statusConfig.type as
                        | 'success'
                        | 'info'
                        | 'danger'
                        | 'warning'
                        | 'primary'
                    },
                    () => statusConfig.text
                  )
              }
            )
          }
        },
        {
          prop: 'created_at',
          label: '操作日期',
          width: 180,
          sortable: true
        },
        {
          prop: 'operation',
          label: '操作',
          width: 70,
          fixed: 'right', // 固定列
          formatter: (row) => {
            return h('div', { style: 'text-align: right' }, [
              hasAuth('auth:admin:logdel') &&
                h(
                  ElTooltip,
                  { content: '删除', placement: 'top' },
                  {
                    default: () =>
                      h(ArtButtonTable, {
                        type: 'delete',
                        onClick: () => deleteRole(row)
                      })
                  }
                )
            ])
          }
        }
      ]
    }
  })

  /**
   * 搜索处理
   * @param params 搜索参数
   */
  const handleSearch = (params: Record<string, any>) => {
    // 处理日期区间参数，把 daterange 转换为 startTime 和 endTime
    const { daterange, ...filtersParams } = params
    const [startTime, endTime] = Array.isArray(daterange) ? daterange : [null, null]

    // 搜索参数赋值
    Object.assign(searchParams, { ...filtersParams, startTime, endTime })
    getData()
  }

  const deleteRole = (row?: RoleListItem) => {
    if (row) {
      ElMessageBox.confirm(`确定要删除【${row.id}】吗？`, '删除用户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(async () => {
        await deleteAdminLogApi([row.id])
        ElMessage.success('删除成功')
        getData()
      })
      return
    }
    // 批量删除
    if (!selectedRows.value.length) {
      ElMessage.warning('请先勾选要删除的用户')
      return
    }
    ElMessageBox.confirm(`确定要删除选中的${selectedRows.value.length}条数据吗？`, '批量删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }).then(async () => {
      const ids = selectedRows.value.map((item) => item.id)
      await deleteAdminLogApi(ids)
      ElMessage.success('批量删除成功')
      getData()
    })
  }
  /**
   * 处理表格行选择变化
   */
  const handleSelectionChange = (selection: RoleListItem[]): void => {
    selectedRows.value = selection
    console.log('选中行数据:', selectedRows.value)
  }
</script>

<style lang="scss" scoped>
  .role-page {
    padding-bottom: 15px;
  }
</style>
